﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using ArgusLight.Fractals2D;

namespace Fractals
{
	public partial class CalculationProgressWindow : ChildWindow
	{
		public bool IsShown { get; private set; }

		public event EventHandler Opened;

		private DateTime startTime;
		private DispatcherTimer timer;
		private string timeFormat;
		//private const string timeFormat = @"hh\:mm\:ss";

		public CalculationProgressWindow()
		{
			InitializeComponent();
			this.progressBar.Value = 0;
			//this.progressBar.IsIndeterminate = true;
			this.IsShown = false;
			this.timeFormat = Localization.Text.CalculationProgressWindowTimeFormat;
			this.timer = new DispatcherTimer();
			this.timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
			this.timer.Tick += timer_Tick;
		}

		void timer_Tick(object sender, EventArgs e)
		{
			Dispatcher.BeginInvoke(this.SetTime);
		}

		void SetTime()
		{
			TimeSpan elapsed = DateTime.Now - this.startTime;
			this.tbTimeElapsed.Text = elapsed.ToString(this.timeFormat);
		}

		protected override void OnOpened()
		{
			base.OnOpened();
			this.progressBar.Value = this.progressBar.Minimum;
			this.IsShown = true;
			if (this.Opened != null)
				this.Opened(this, new EventArgs());
			this.startTime = DateTime.Now;
			this.timer.Start();
		}

		protected override void OnClosed(EventArgs e)
		{
			this.timer.Stop();
			this.tbTimeElapsed.Text = string.Empty;
			base.OnClosed(e);
			this.IsShown = false;
		}

		public void UpdateProgress(object sender, ProgressUpdatedArgs e)
		{
			if (e.Progress >= this.progressBar.Minimum && e.Progress <= this.progressBar.Maximum)
				this.progressBar.Value = e.Progress;
			int[] userState = (int[])e.UserState;
			this.tbPixelsCalculating.Text = userState[0].ToString();
			this.tbPixelsCalculated.Text = userState[1].ToString();
		}

		public event RoutedEventHandler CancelRequested;

		private void bCancel_Click(object sender, RoutedEventArgs e)
		{
			if (this.CancelRequested != null)
				this.CancelRequested(this, new RoutedEventArgs());
		}
	}
}

